<script setup lang="ts">
import AccountSecurity from "~/components/setUp/AccountSecurity.vue";
import { useUserStore } from "~/store/useUser";
import { getUserInfo, putProfile } from "~/api/user";
import { fileUploadAPI, avatarUploadAPI } from "~/api/fileUpload";
import { useImageCache } from "~/composables/useImageCache";
import test from "~/utils/test";
import { ElMessage } from "element-plus";

useSeoMeta({
  title: "设置 - 技能猴子",
  ogTitle: "设置 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

const { preloadImages, imageUrlCache, getCoverImage } = useImageCache();
const userStore = useUserStore();
const menuIndex = ref(0);
const menuChange = (index: number) => {
  menuIndex.value = index;
};

const userInfo = ref({});
const loading = ref(false);

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true;
    const res = await getUserInfo();
    if (res.code === 200 && res.data) {
      const data = res.data;
      
      // 处理 avatar 字段，如果是 OSS ID，则加载 OSS 图片
      if (data.avatar && typeof data.avatar === 'string' && !data.avatar.includes('http')) {
        // 是 OSS ID，预加载图片 URL
        await preloadImages([data.avatar]);
        // 从缓存中获取或使用 getCoverImage
        const cachedUrl = imageUrlCache.value?.[data.avatar];
        data.avatar = cachedUrl || getCoverImage(data.avatar);
      }
      
      userInfo.value = data;
    }
  } catch (err) {
    console.error('获取用户信息失败:', err);
    // 如果接口调用失败，使用 store 中的用户信息作为后备
    userInfo.value = userStore.getUserInfo;
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  // 先使用 store 中的用户信息，然后调用接口获取最新数据
  userInfo.value = userStore.getUserInfo;
  fetchUserInfo();
});

watch(
  () => userStore.getUserInfo,
  (newValue, oldValue) => {
    // 如果接口数据还未加载，使用 store 中的数据
    if (!userInfo.value || Object.keys(userInfo.value).length === 0) {
      userInfo.value = newValue;
    } else if (newValue && Object.keys(newValue).length > 0) {
      // 如果 store 中的用户信息已更新（比如手机号），同步更新本地 userInfo
      // 特别检查手机号是否变化
      if (newValue.phonenumber && newValue.phonenumber !== userInfo.value?.phonenumber) {
        userInfo.value = { ...userInfo.value, ...newValue };
      }
    }
  },
  { deep: true }
);

// 账号信息表单相关
const phonenumber = ref("");
const nickName = ref("");
const form = ref({
  wxchat: "",
  flyBook: "",
});
const wxchatError = ref("");
const phonenumberError = ref("");

// 初始化表单数据
const initForm = () => {
  form.value = {
    wxchat: userInfo.value?.wxchat || "",
    flyBook: userInfo.value?.flyBook || "",
  };
  // 优先使用 userInfo，其次使用 store 的 getUserInfo getter
  phonenumber.value = userInfo.value?.phonenumber || userStore.getUserInfo?.phonenumber || "";
  nickName.value = userInfo.value?.nickName || userStore.getUserInfo?.nickName || "";
};

// 监听 userInfo 的变化
watch(
  () => userInfo.value,
  (newValue) => {
    if (newValue && Object.keys(newValue).length > 0) {
      initForm();
    }
  },
  { deep: true, immediate: true }
);

// 监听昵称变化
watch(
  () => userInfo.value?.nickName,
  (newValue) => {
    if (newValue) {
      nickName.value = newValue;
    }
  },
  { immediate: true }
);

// 微信号输入验证
const wxchatInput = (e) => {
  if (e.length > 20) {
    return (wxchatError.value = "微信号不能超过20个字符");
  }
  // 不能包含特殊字符
  if (/[^\w\s]/.test(e)) {
    return (wxchatError.value = "微信号不能包含特殊字符");
  }
  // 不能有中文字符串
  if (/[\u4e00-\u9fa5]/.test(e)) {
    return (wxchatError.value = "微信号不能包含中文字符");
  }
  wxchatError.value = "";
};

const wxchatBlurValidate = () => {
  if (!form.value.wxchat) {
    wxchatError.value = "微信号不能为空";
    return;
  }
  if (!form.value.wxchat.trim()) {
    wxchatError.value = "微信号不能为空";
    return;
  }
  wxchatError.value = "";
};

// 上传头像
const fileInput = async (e) => {
  const file = e.target.files[0];
  if (!file) return;
  
  // 验证文件类型
  const validTypes = ['image/png', 'image/jpeg', 'image/jpg'];
  if (!validTypes.includes(file.type)) {
    return ElMessage.error("请上传 PNG、JPG 或 JPEG 格式的图片");
  }
  
  // 验证文件大小（10MB）
  const maxSize = 10 * 1024 * 1024;
  if (file.size > maxSize) {
    return ElMessage.error("图片大小不能超过 10MB");
  }
  
  try {
    // 先尝试使用专门的头像上传接口，字段名需要使用 avatarfile
    const avatarFormData = new FormData();
    avatarFormData.append("avatarfile", file);
    
    try {
      const res = await avatarUploadAPI(avatarFormData);
      if (res.code === 200) {
        ElMessage.success("上传成功");
        await userStore.userInfoAction();
        await fetchUserInfo();
        // 重置文件输入，允许重复上传同一文件
        e.target.value = '';
        return;
      } else {
        ElMessage.error(res.msg || "上传失败");
        return;
      }
    } catch (avatarErr) {
      // 如果头像上传接口不可用，使用通用上传接口，然后更新头像
      console.log("头像上传接口不可用，使用通用上传接口:", avatarErr);
    }
    
    // 使用通用上传接口，字段名使用 file
    const formData = new FormData();
    formData.append("file", file);
    
    const res = await fileUploadAPI(formData);
    if (res.code === 200 && res.data) {
      // 获取 ossId
      const ossId = res.data.ossId || res.data;
      if (ossId) {
        // 通过 putProfile 更新头像
        const updateRes = await putProfile({ avatar: ossId });
        if (updateRes.code === 200) {
          ElMessage.success("上传成功");
          await userStore.userInfoAction();
          await fetchUserInfo();
          // 重置文件输入，允许重复上传同一文件
          e.target.value = '';
        } else {
          ElMessage.error(updateRes.msg || "更新头像失败");
        }
      } else {
        ElMessage.error("未获取到头像ID");
      }
    } else {
      ElMessage.error(res.msg || "上传失败");
    }
  } catch (e) {
    console.error("上传头像失败:", e);
    ElMessage.error("上传失败，请重试");
  }
};

// 保存所有信息（昵称、手机号、微信号、飞书号）
const saveAccountInfo = async () => {
  // 验证昵称
  if (test.empty(nickName.value)) {
    return ElMessage.error("请输入昵称");
  }
  // 验证微信号
  if (!form.value.wxchat) {
    return ElMessage.error("微信号不能为空");
  }
  if (!form.value.wxchat.trim()) {
    return ElMessage.error("微信号不能为空");
  }
  try {
    // 同时保存昵称、手机号、微信号、飞书号
    await putProfile({
      nickName: nickName.value,
      phonenumber: phonenumber.value,
      wxchat: form.value.wxchat,
      flyBook: form.value.flyBook,
    });
    ElMessage.success("更新成功");
    await userStore.userInfoAction();
    await fetchUserInfo();
  } catch (e) {
    console.log(e);
  }
};
</script>

<template>
  <BaseHeaderMenuWhite bg-color="white" />
  <div class="body">
    <div class="set-up">
      <div class="left">
        <span :class="{ active: menuIndex === 0 }" @click="menuChange(0)"
          >账号信息</span
        >
        <span :class="{ active: menuIndex === 1 }" @click="menuChange(1)"
          >账号与安全</span
        >
      </div>
      <div class="right">
        <div v-if="menuIndex === 0" class="acc-info">
          <p class="title">个人头像</p>
          <p class="tips">真实头像有益于他人识别你，请勿使用他人头像</p>
          <div class="head">
            <img v-if="userInfo.avatar" :src="userInfo.avatar" alt="" />
            <img v-else src="~/assets/app-mj.png" alt="" />
            <button>
              上传头像
              <input type="file" accept=" image/png,image/jpeg" @input="fileInput" />
            </button>
          </div>
          <div class="nickname">
            <span class="label"><span>*</span> 昵称</span>
            <el-input
              type="text"
              v-model="nickName"
              placeholder="请输入昵称"
            />
          </div>
          <p class="title">联系方式</p>
          <div class="nickname">
            <span class="label"><span>*</span> 手机号码</span>
            <el-input
              type="text"
              v-model="phonenumber"
              :placeholder="userInfo.phonenumber || '请输入手机号码'"
              maxlength="11"
              show-word-limit
              :disabled="true"
            />
            <p class="error" v-if="phonenumberError">{{ phonenumberError }}</p>
          </div>
          <div class="nickname">
            <span class="label"><span>*</span> 微信号</span>
            <el-input
              type="text"
              maxlength="20"
              :show-word-limit="true"
              v-model="form.wxchat"
              :placeholder="userInfo.wxchat || '请输入微信号'"
              @blur="wxchatBlurValidate"
              @input="wxchatInput"
            />
            <p class="error" v-if="wxchatError">{{ wxchatError }}</p>
          </div>
          <div class="nickname">
            <span class="label"> 飞书号</span>
            <el-input
              type="text"
              maxlength="20"
              :show-word-limit="true"
              v-model="form.flyBook"
              :placeholder="userInfo.flyBook || '请输入飞书号'"
            />
          </div>
          <span class="save" @click="saveAccountInfo">保存</span>
        </div>
        <AccountSecurity v-if="menuIndex === 1" :userInfo="userInfo" @userInfoUpdated="fetchUserInfo" />
      </div>
    </div>
  </div>
  <BaseFooter />
</template>

<style scoped lang="scss">
.body {
  padding-top: 80px;
  background: #f9f9f9;
}
.set-up {
  width: 1100px;
  margin: 0 auto;
  display: flex;
  padding-top: 32px;
  padding-bottom: 36px;
  .left {
    flex: 0 0 200px;
    height: fit-content;
    display: flex;
    flex-direction: column;
    background: #ffffff;
    box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
    border-radius: 16px 16px 16px 16px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    padding: 28px 24px;
    margin-right: 24px;
    box-sizing: border-box;
    span {
      font-size: 16px;
      color: #191e28;
      margin-bottom: 18px;
      cursor: pointer;
      &:last-child {
        margin-bottom: 0;
      }
      &.active {
        color: #1dbf73;
        font-weight: bold;
        position: relative;
        &:before {
          content: "";
          position: absolute;
          width: 3px;
          height: 30px;
          background: #1dbf73;
          top: 50%;
          margin-top: -15px;
          left: -24px;
        }
      }
    }
  }
  .right {
    flex: 1;
    background: #ffffff;
    box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
    border-radius: 16px 16px 16px 16px;
    border: 1px solid rgba(25, 30, 40, 0.08);
  }
}

.acc-info {
  padding: 24px 24px 48px;
}
.error {
  color: #ff4f4f;
  font-size: 12px;
  margin-top: 8px;
}
.title {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
  color: #191e28;
}
.tips {
  font-size: 12px;
  color: rgba(25, 30, 40, 0.36);
  margin-bottom: 20px;
}
.head {
  display: flex;
  align-items: center;
  margin-bottom: 40px;
  img {
    width: 80px;
    height: 80px;
    margin-right: 10px;
    border-radius: 50%;
  }
  button {
    width: 92px;
    height: 42px;
    background: #f9fafb;
    border-radius: 6px 6px 6px 6px;
    position: relative;
    border: none;
    color: #191e28;
    cursor: pointer;
    &:hover {
      background: #eeeeef;
    }
    input {
      position: absolute;
      opacity: 0;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      cursor: pointer;
    }
  }
}
.nickname {
  display: flex;
  flex-direction: column;
  margin-bottom: 36px;
  .label {
    color: rgba(25, 30, 40, 1);
    font-size: 16px;
    margin-bottom: 12px;
    span {
      color: #ff4f4f;
    }
  }
  input {
    width: 324px;
    height: 48px;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    padding: 0 12px;
    outline: none;
  }
}
.save {
  display: block;
  width: 160px;
  height: 48px;
  background: #1dbf73;
  border-radius: 8px 8px 8px 8px;
  color: #fff;
  cursor: pointer;
  line-height: 48px;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}
</style>

<style lang="scss">
.set-up .nickname .el-input {
  width: 324px;
  height: 48px;
  border-radius: 8px 8px 8px 8px;
  padding: 0;
  outline: none;
}
.set-up .nickname .el-input__wrapper {
  border-radius: 8px 8px 8px 8px;
  border: none;
}
</style>
